/**
 * 
 */
package info.niwota.webagent.peer;

import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;

/**
 * @author qiangli
 * 
 */
public class PeerRegistery {
	private static final String PEERSTORE = "peerstore";
	private static final String OBJECT = "PeerObject";

	private static DatastoreService datastore = DatastoreServiceFactory
			.getDatastoreService();

	public static Key insert(PeerEntry obj) throws Exception {
		Entity e = createEntry(obj);
		return datastore.put(e);
	}

	private static Entity createEntry(PeerEntry o) {
		Key key = KeyFactory.createKey("PeerRegistry", PEERSTORE);
		Entity e = new Entity(OBJECT, key);
		e.setProperty("jid", o.getJid());
		e.setProperty("ip", o.getIp());
		e.setProperty("port", o.getPort());
		e.setProperty("name", o.getName());
		e.setProperty("message", o.getMessage());
		e.setProperty("avatar", o.isAvatar());
		e.setProperty("creation", System.currentTimeMillis());
		return e;
	}
	
	private static PeerEntry toPeerEntry(Entity e) {
		if (e == null) {
			return null;
		}
		PeerEntry o = new PeerEntry();
		o.setJid((String) e.getProperty("jid"));
		o.setIp((String) e.getProperty("ip"));
		o.setPort((String) e.getProperty("port"));
		o.setName((String) e.getProperty("name"));
		o.setMessage((String) e.getProperty("message"));
		o.setAvatar((Boolean) e.getProperty("avatar"));
		o.setCreation((Long) e.getProperty("creation"));
		
		o.setKey(e.getKey());
		
		return o;
	}
	
	public static void delete(String jid) throws Exception {
		try {
			Query q = new Query(OBJECT);
			q.addFilter("jid", Query.FilterOperator.EQUAL,
					jid);
			PreparedQuery pq = datastore.prepare(q);
			Entity e = pq.asSingleEntity();
			datastore.delete(e.getKey());
		} catch (Exception e) {
			throw e;
		}
	}

	public static PeerEntry get(String jid) {
		Query q = new Query(OBJECT);
		q.addFilter("jid", Query.FilterOperator.EQUAL, jid);
		PreparedQuery pq = datastore.prepare(q);
		Entity e = pq.asSingleEntity();
		return toPeerEntry(e);
	}

	public static List<Entity> list(int offset, int max) {
		Query q = new Query(OBJECT);
		q.addSort("creation", SortDirection.DESCENDING);
		PreparedQuery pq = datastore.prepare(q);
		return pq.asList(FetchOptions.Builder.withLimit(max).offset(offset));
	}
	
}
